/*
 * @Author: liuYang codkly@gmail.com
 * @Date: 2022-12-05 17:21:42
 * @LastEditors: liuYang codkly@gmail.com
 * @LastEditTime: 2022-12-08 14:00:53
 * @FilePath: \coding\nest\blog_alpha\src\user\user.service.ts
 * @Description:
 * 暂无备注
 */
import { Injectable, HttpException } from '@nestjs/common';
import { UserEntity } from './user.entity';
import { UserinfoEntity } from '../userinfo/userinfo.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, Raw, In } from 'typeorm';
import { cryptoString } from '../../utils/index';
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private userRepository: Repository<UserEntity>,
    @InjectRepository(UserinfoEntity)
    private userinfoRepository: Repository<UserinfoEntity>,
  ) {}

  // 增加

  async create(createUserDto: any): Promise<any> {
    const { name, password } = createUserDto;
    createUserDto.password = cryptoString(password);

    delete createUserDto.id;
    const isExist = await this.userRepository.count({
      where: {
        name,
      },
    });
    console.log(isExist);
    if (isExist > 0) {
      return {
        code: -1,
        msg: '账号已存在',
        data: null,
      };
    }
    // 新增一条空的关联数据
    const info = new UserinfoEntity();
    await this.userinfoRepository.save(info);
    createUserDto['info'] = info;
    // 新增账号
    try {
      let res = await this.userRepository.save(createUserDto);
      if (res) {
        return {
          data: '注册成功',
        };
      } else {
        return {
          code: -1,
          msg: '注册失败',
          data: null,
        };
      }
    } catch (error) {
      return {
        code: -1,
        msg: error,
        data: null,
      };
    }
  }

  // 软删除
  async delete(removeUserDto: any): Promise<any> {
    const { ids } = removeUserDto;
    return this.userRepository.softDelete(ids);
  }
  //   查详情
  async findOne(id: string): Promise<any> {
    let res = await this.userRepository
      .createQueryBuilder('user')
      .where([{ id: id }])
      .leftJoinAndSelect('user.info', 'id')
      .getOne();

    return {
      data: res,
    };
  }

  // 更新
  async update(updateUserData): Promise<any> {
    const { id, updateUserDto } = updateUserData;
    // updateUserDto.updatedAt = new Date();
    const { name } = updateUserDto;

    const isExist = await this.userRepository.count({
      where: {
        name,
      },
    });
    if (isExist > 1) {
      return {
        statusCode: 201,
        message: '已存在',
      };
    }
    return await this.userRepository.update(id, updateUserDto);
  }

  // 列表
  async findAll(query: any): Promise<any> {
    const { keyword, page = 1, limit = 10 } = query;
    const skip = (page - 1) * limit;

    let whereParams = {};
    if (keyword) {
      whereParams = Object.assign(whereParams, {
        name: Like(`%${keyword}%`),
      });
    }

    // let params = {
    //   skip,
    //   take: limit,
    // };

    // params = Object.assign(
    //     {
    //       select: ['id', 'name', 'updated_at', 'status','info.avatar'],
    //     },
    //   params,
    //   {
    //     where: whereParams,
    //   },
    //   {
    //     order: {
    //       updated_at: 'DESC',
    //     },
    //   },
    //   { relations: ['info'] },

    // );
    // const [data, total] = await this.userRepository.findAndCount(params);

    let data = await this.userRepository
      .createQueryBuilder('user')
      .where(whereParams)
      .take(limit)
      .skip(skip)
      .orderBy({
        'user.updated_at': 'DESC',
      })
      .select(['user.id', 'user.name','user.email','user.updated_at',]) // 'info.count', 'info.avatar'
      .leftJoinAndSelect('user.info', 'info') // bar is the joined table
      .getMany();

    return {
      data: {
        list: data,
      },
    };
  }
}
